package com.yp.loading.utils;

import android.content.Context;
import android.util.TypedValue;

/**
 * 作者：刘江飞
 * 时间：2020/6/18
 * 邮箱：642371742@qq.com
 * 描述：尺寸转换工具类
 */
public class DensityUtil {
    private static DensityUtil mDensityUtil;

    public static DensityUtil getInstance() {
        if (mDensityUtil == null) {

            synchronized (DensityUtil.class) {
                if (mDensityUtil == null) {
                    mDensityUtil = new DensityUtil();
                }
            }
        }
        return mDensityUtil;
    }

    /**
     * dp转px
     */
    public int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }

    /**
     * sp转px
     */
    public int sp2px(Context context, float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spVal, context.getResources().getDisplayMetrics());
    }

    /**
     * px转dp
     */
    public float px2dp(Context context, float pxVal) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxVal / scale);
    }

    /**
     * px转sp
     */
    public float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }
}
